package com.edu.buaa;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class BirthInputActivity extends AppCompatActivity {
    private static final String TAG = "BirthInputActivity";

    private RadioGroup rgGender;
    private Spinner spYear, spMonth, spDay, spHour;
    private Button btnSubmit, btnLoadPrevious;
    private TextView tvTitle;
    private DatabaseHelper databaseHelper;
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_birth_input);

        Log.d(TAG, "BirthInputActivity onCreate");

        initViews();
        setupSpinners();
        
        // 获取用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        userId = sharedPreferences.getInt("user_id", -1);
        databaseHelper = new DatabaseHelper(this);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitBirthData();
            }
        });

        btnLoadPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadPreviousData();
            }
        });

        // 检查是否有之前的数据
        checkPreviousData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 创建菜单
        getMenuInflater().inflate(R.menu.menu_birth_input, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_logout) {
            // 退出登录
            logout();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // 物理返回键提示退出登录
        showLogoutConfirmation();
    }

    private void showLogoutConfirmation() {
        new android.app.AlertDialog.Builder(this)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> logout())
                .setNegativeButton("取消", null)
                .show();
    }

    private void logout() {
        // 清除登录状态
        SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();

        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();

        // 跳转到登录页面
        Intent intent = new Intent(BirthInputActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private void initViews() {
        Log.d(TAG, "Initializing BirthInputActivity views");
        tvTitle = findViewById(R.id.tvTitle);
        rgGender = findViewById(R.id.rgGender);
        spYear = findViewById(R.id.spYear);
        spMonth = findViewById(R.id.spMonth);
        spDay = findViewById(R.id.spDay);
        spHour = findViewById(R.id.spHour);
        btnSubmit = findViewById(R.id.btnSubmit);
        btnLoadPrevious = findViewById(R.id.btnLoadPrevious);

        // 标题栏按钮
        Button btnBack = findViewById(R.id.btnBack);
        Button btnLogout = findViewById(R.id.btnLogout);

        // 设置标题
        tvTitle.setText("输入生辰八字");

        // 设置按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLogoutConfirmation();
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }

    private void setupSpinners() {
        // 年份：1900-当前年份
        Integer[] years = new Integer[124];
        for (int i = 0; i < 124; i++) {
            years[i] = 1900 + i;
        }
        ArrayAdapter<Integer> yearAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, years);
        yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spYear.setAdapter(yearAdapter);
        spYear.setSelection(88); // 默认1988年

        // 月份：1-12
        Integer[] months = new Integer[12];
        for (int i = 0; i < 12; i++) {
            months[i] = i + 1;
        }
        ArrayAdapter<Integer> monthAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, months);
        monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMonth.setAdapter(monthAdapter);

        // 日期：1-31
        Integer[] days = new Integer[31];
        for (int i = 0; i < 31; i++) {
            days[i] = i + 1;
        }
        ArrayAdapter<Integer> dayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days);
        dayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spDay.setAdapter(dayAdapter);

        // 时辰
        String[] hours = {"子时 (23:00-00:59)", "丑时 (01:00-02:59)", "寅时 (03:00-04:59)", 
                         "卯时 (05:00-06:59)", "辰时 (07:00-08:59)", "巳时 (09:00-10:59)",
                         "午时 (11:00-12:59)", "未时 (13:00-14:59)", "申时 (15:00-16:59)",
                         "酉时 (17:00-18:59)", "戌时 (19:00-20:59)", "亥时 (21:00-22:59)"};
        ArrayAdapter<String> hourAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, hours);
        hourAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spHour.setAdapter(hourAdapter);
        spHour.setSelection(2); // 默认寅时
    }

    private void submitBirthData() {
        // 获取性别
        int selectedGenderId = rgGender.getCheckedRadioButtonId();
        if (selectedGenderId == -1) {
            Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
            return;
        }
        RadioButton selectedGender = findViewById(selectedGenderId);
        String gender = selectedGender.getText().toString();

        // 获取生辰信息
        int year = (int) spYear.getSelectedItem();
        int month = (int) spMonth.getSelectedItem();
        int day = (int) spDay.getSelectedItem();
        int hour = spHour.getSelectedItemPosition(); // 0-11 对应12时辰

        String solarDate = year + "年" + month + "月" + day + "日";

        // 保存到数据库
        if (databaseHelper.saveBirthData(userId, gender, year, month, day, hour, solarDate)) {
            Toast.makeText(this, "生辰信息保存成功", Toast.LENGTH_SHORT).show();
            
            // 跳转到排盘页面，传递生辰数据
            Intent intent = new Intent(BirthInputActivity.this, MainActivity.class);
            intent.putExtra("gender", gender);
            intent.putExtra("year", year);
            intent.putExtra("month", month);
            intent.putExtra("day", day);
            intent.putExtra("hour", hour);
            intent.putExtra("solar_date", solarDate);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkPreviousData() {
        if (userId != -1) {
            android.database.Cursor cursor = databaseHelper.getBirthData(userId);
            if (cursor != null && cursor.moveToFirst()) {
                btnLoadPrevious.setVisibility(View.VISIBLE);
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private void loadPreviousData() {
        if (userId != -1) {
            android.database.Cursor cursor = databaseHelper.getBirthData(userId);
            if (cursor != null && cursor.moveToFirst()) {
                String gender = cursor.getString(cursor.getColumnIndexOrThrow("gender"));
                int year = cursor.getInt(cursor.getColumnIndexOrThrow("birth_year"));
                int month = cursor.getInt(cursor.getColumnIndexOrThrow("birth_month"));
                int day = cursor.getInt(cursor.getColumnIndexOrThrow("birth_day"));
                int hour = cursor.getInt(cursor.getColumnIndexOrThrow("birth_hour"));

                // 设置性别
                if (gender.equals("男")) {
                    rgGender.check(R.id.rbMale);
                } else {
                    rgGender.check(R.id.rbFemale);
                }

                // 设置年份
                for (int i = 0; i < spYear.getCount(); i++) {
                    if (spYear.getItemAtPosition(i).equals(year)) {
                        spYear.setSelection(i);
                        break;
                    }
                }

                // 设置月份
                spMonth.setSelection(month - 1);

                // 设置日期
                spDay.setSelection(day - 1);

                // 设置时辰
                spHour.setSelection(hour);

                Toast.makeText(this, "已加载上次保存的生辰信息", Toast.LENGTH_SHORT).show();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}